package geon.dao;

import geon.config.Conn;
import geon.model.Contador;
import geon.utils.DataUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DaoGenerico {

	private Connection conn = null;
	private DaoContador cont;

	public DaoGenerico() {
		try {
			conn = DriverManager.getConnection(Conn.getConn(), Conn.getUser(), Conn.getPass());			
		} catch (Exception e) {
			Logger.getLogger(DaoGenerico.class.getName()).log(Level.SEVERE, null, e);
		}
	}

	public void begin() throws SQLException{
		conn.setAutoCommit(false);
	}
	
	public void commit() throws SQLException{
		conn.commit();
	}
	
	public void rollback() throws SQLException{
		conn.rollback();
	}
	
	public Statement getStatement() throws SQLException {
		return conn.createStatement();
	}

	public PreparedStatement getStatement(String s) throws SQLException {
		return conn.prepareStatement(s);
	}

	public ResultSet executeQuery(String s, Object... params) throws SQLException {
		PreparedStatement ps = getStatement(s);
		for (int i = 0; i < params.length; i++) {
			ps.setObject(i + 1, params[i]);
		}
		return ps.executeQuery();
	}

	public int executeCommand(String s, Object... params) throws SQLException {
		PreparedStatement ps = getStatement(s);
		for (int i = 0; i < params.length; i++) {
			ps.setObject(i + 1, params[i]);
		}
		int resultado = ps.executeUpdate();
		ps.close();
		return resultado;
	}
	
	public Integer getNextId() throws SQLException {			
		Contador resultado = cont.getInstance().get();	
		if ((resultado == null) || (!resultado.getCodigo().equals(Integer.parseInt(DataUtils.dataFormat("yyyyMM"))))) {
			return cont.getInstance().add(resultado);	
		} else {
			cont.getInstance().inc(resultado.getCodigo());					
			return cont.getInstance().pes();
		}			
	}

	public Integer getNextId(String tabela, String chave) throws SQLException {
		return cont.getInstance().inc(tabela, chave);
	}

}
